document.addEventListener('DOMContentLoaded', () => {
    // 初始化标签页切换
    initializeTabs();
    
    // 获取当前标签页的资源
    getCurrentTabResources();
    
    // 初始化下载所有按钮的右键菜单
    initializeContextMenus();
    
    // 监听来自 content script 的资源更新消息
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
        if (request.action === 'resourcesUpdated' && request.resources) {
            displayResources('images', request.resources.images || []);
            displayResources('videos', request.resources.videos || []);
            displayResources('audios', request.resources.audios || []);
            initializeDownloadAllButtons(request.resources);
        }
    });
});

// 初始化标签页切换功能
function initializeTabs() {
    const tabs = document.querySelectorAll('.tab-button');
    tabs.forEach(tab => {
        tab.addEventListener('click', () => {
            // 移除所有活动状态
            document.querySelectorAll('.tab-button').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
            
            // 添加当前标签的活动状态
            tab.classList.add('active');
            const tabId = tab.getAttribute('data-tab');
            document.getElementById(tabId).classList.add('active');
        });
    });
}

// 获取当前标签页的资源
function getCurrentTabResources() {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (!tabs || tabs.length === 0) {
            console.error('No active tab found');
            displayError('无法获取当前标签页信息');
            return;
        }

        const currentTab = tabs[0];
        
        // 注入内容脚本
        chrome.scripting.executeScript({
            target: { tabId: currentTab.id },
            files: ['content.js']
        }).then(() => {
            // 脚本注入成功后发送消息
            chrome.tabs.sendMessage(currentTab.id, { action: 'getResources' }, (response) => {
                if (chrome.runtime.lastError) {
                    console.error('Error:', chrome.runtime.lastError);
                    displayError('无法与页面通信');
                    return;
                }
                
                if (response) {
                    displayResources('images', response.images || []);
                    displayResources('videos', response.videos || []);
                    displayResources('audios', response.audios || []);
                    
                    // 初始化下载所有按钮
                    initializeDownloadAllButtons(response);
                }
            });
        }).catch(error => {
            console.error('Script injection failed:', error);
            displayError('脚本注入失败');
        });
    });
}

// 显示错误信息
function displayError(message) {
    const containers = ['image-list', 'video-list', 'audio-list'];
    containers.forEach(containerId => {
        const container = document.getElementById(containerId);
        if (container) {
            container.innerHTML = `<div class="error-message">${message}</div>`;
        }
    });
}

// 显示资源列表
function displayResources(type, resources) {
    const container = document.getElementById(`${type.replace('s', '')}-list`);
    if (!container) {
        console.error(`Container not found: ${type.replace('s', '')}-list`);
        return;
    }

    container.innerHTML = '';
    
    if (!resources || resources.length === 0) {
        container.innerHTML = `<div class="no-resources">未找到${getResourceTypeName(type)}资源</div>`;
        return;
    }
    
    resources.forEach(resource => {
        if (resource && resource.src) {
            const item = createResourceItem(resource);
            container.appendChild(item);
        }
    });
}

// 创建资源项
function createResourceItem(resource) {
    const item = document.createElement('div');
    item.className = 'resource-item';
    
    // 预览
    if (resource.type === 'image') {
        const previewContainer = document.createElement('div');
        previewContainer.className = 'preview-container';
        
        const preview = document.createElement('img');
        preview.className = 'resource-preview';
        preview.alt = resource.alt || '图片预览';
        preview.loading = 'lazy'; // 启用延迟加载
        
        // 创建一个临时的 img 元素来检查图片是否可以加载
        const tempImg = new Image();
        tempImg.onload = () => {
            preview.src = resource.src;
            preview.style.display = 'block';
            previewContainer.querySelector('.preview-placeholder')?.remove();
        };
        tempImg.onerror = () => {
            preview.style.display = 'none';
            const placeholder = document.createElement('div');
            placeholder.className = 'preview-placeholder';
            placeholder.textContent = '图片预览不可用';
            previewContainer.appendChild(placeholder);
        };
        tempImg.src = resource.src;

        previewContainer.appendChild(preview);
        item.appendChild(previewContainer);
    } else if (resource.type === 'video') {
        const previewContainer = document.createElement('div');
        previewContainer.className = 'preview-container video-preview';
        
        if (resource.poster) {
            const poster = document.createElement('img');
            poster.src = resource.poster;
            poster.className = 'resource-preview';
            poster.alt = '视频预览';
            previewContainer.appendChild(poster);
        } else {
            const placeholder = document.createElement('div');
            placeholder.className = 'preview-placeholder';
            placeholder.innerHTML = '<span class="material-icons">play_circle</span>';
            previewContainer.appendChild(placeholder);
        }
        
        item.appendChild(previewContainer);
    } else {
        const previewContainer = document.createElement('div');
        previewContainer.className = 'preview-container audio-preview';
        const placeholder = document.createElement('div');
        placeholder.className = 'preview-placeholder';
        placeholder.innerHTML = '<span class="material-icons">audiotrack</span>';
        previewContainer.appendChild(placeholder);
        item.appendChild(previewContainer);
    }
    
    // 信息
    const info = document.createElement('div');
    info.className = 'resource-info';
    
    const nameContainer = document.createElement('div');
    nameContainer.className = 'resource-name';
    nameContainer.title = resource.filename || resource.src; // 添加悬停提示
    nameContainer.textContent = resource.filename || '未命名文件';
    
    const detailsContainer = document.createElement('div');
    detailsContainer.className = 'resource-details';
    
    // 添加尺寸信息（如果有）
    if (resource.width && resource.height) {
        const dimensions = document.createElement('span');
        dimensions.className = 'resource-dimensions';
        dimensions.textContent = `${resource.width} × ${resource.height}`;
        detailsContainer.appendChild(dimensions);
    }
    
    // 添加持续时间（如果是音频且有时长）
    if (resource.type === 'audio' && resource.duration) {
        const duration = document.createElement('span');
        duration.className = 'resource-duration';
        duration.textContent = formatDuration(resource.duration);
        detailsContainer.appendChild(duration);
    }
    
    const downloadBtn = document.createElement('button');
    downloadBtn.className = 'download-btn';
    downloadBtn.textContent = '下载';
    downloadBtn.addEventListener('click', () => {
        chrome.runtime.sendMessage({
            action: 'download',
            url: resource.src,
            filename: resource.filename || `${resource.type}_${Date.now()}.${getDefaultExtension(resource.type)}`
        });
    });
    
    info.appendChild(nameContainer);
    info.appendChild(detailsContainer);
    info.appendChild(downloadBtn);
    item.appendChild(info);
    
    return item;
}

// 格式化时长显示
function formatDuration(seconds) {
    if (!seconds || isNaN(seconds)) return '';
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = Math.floor(seconds % 60);
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
}

// 初始化下载所有按钮
function initializeDownloadAllButtons(resources) {
    const buttons = document.querySelectorAll('.download-all-btn');
    buttons.forEach(button => {
        const type = button.getAttribute('data-type');
        if (resources[type] && resources[type].length > 0) {
            button.addEventListener('click', () => {
                chrome.runtime.sendMessage({
                    action: 'downloadAll',
                    resources: resources[type]
                });
            });
            button.disabled = false;
        } else {
            button.disabled = true;
        }
    });
}

// 初始化右键菜单
function initializeContextMenus() {
    const tabContents = document.querySelectorAll('.tab-content');
    tabContents.forEach(content => {
        content.addEventListener('contextmenu', (e) => {
            e.preventDefault();
            const type = content.id;
            const downloadAllBtn = content.querySelector('.download-all-btn');
            if (downloadAllBtn && !downloadAllBtn.disabled) {
                downloadAllBtn.click();
            }
        });
    });
}

// 获取资源类型名称
function getResourceTypeName(type) {
    const types = {
        'images': '图片',
        'videos': '视频',
        'audios': '音频',
        'image': '图片',
        'video': '视频',
        'audio': '音频'
    };
    return types[type] || '未知类型';
}

// 获取默认文件扩展名
function getDefaultExtension(type) {
    const extensions = {
        'image': 'jpg',
        'video': 'mp4',
        'audio': 'mp3'
    };
    return extensions[type] || 'unknown';
} 